package com.example.administrator.myjdlc.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.example.administrator.myjdlc.R;
import com.example.administrator.myjdlc.base.BaseActivity;
import com.example.administrator.myjdlc.bean.ServiceData;
import com.example.administrator.myjdlc.cache.CacheManager;
import com.example.administrator.myjdlc.cache.CacheManagerConst;
import com.example.administrator.myjdlc.common.Code;
import com.example.administrator.myjdlc.common.Const;
import com.example.administrator.myjdlc.net.BackData;
import com.example.administrator.myjdlc.net.NetLoadListener;
import com.example.administrator.myjdlc.net.NetService;
import com.example.administrator.myjdlc.sharedpreferences.SPConst;
import com.example.administrator.myjdlc.sharedpreferences.SPUtils;
import com.example.administrator.myjdlc.ui.ToastView;
import com.example.administrator.myjdlc.utils.CommonUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;


/**
 * Created by Administrator on 2017/4/16.
 */

public class LoadingActivity extends BaseActivity {
    private String url= Const.HttpConst.GET_LOADING_IAMGE;
    /**
     * 版本检测
     */
    static final int VERSION=100;
    /**
     * Toast
     */
    ToastView toast;
    /**
     * 网络请求工具类
     */
    String formatType=null;
    /**
     * 添加成功
     */
    /**
     * gif
     */
    private GifImageView gifView;

    /**
     * 静态图片
     */
    /**
     * 本地图片
     */
    static final int LOCAL_GIF=102;

    /**
     * 本地图片
     */
    static final int NET_GIF=103;

    /**
     * 本地图片
     */
    String isGuide;
    /**
     * 网络加载出来的图片
     */

    private Bitmap bit;
    /**
     * gifView
     */
    GifDrawable gbDrawable;
    static final int NET_JPG=104;
    private ImageView ivLoading;
    static final int DOWNLOAD_SUCCESS=101;
    private NetService netService;
    Handler mHandler=new Handler() {

        private GifDrawable gbDrawable;

        @SuppressLint("NewApi")
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case VERSION:
                    BackData backData = (BackData) msg.obj;
                    //判断网络链接结果
                    if (backData.getNetResultCode() == Code.NetStatusCode.SUCCESS) {
                        //接口验证
                        //if(backData.getCode()==ServiceCode.SUCCESS){
                        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
                        ServiceData data = gson.fromJson(backData.getObject().toString(), ServiceData.class);
                        //接口验证
                        if (data.getCode() == Code.ServiceCode.SUCCESS) {
                            if (data.getData() != null) {
                                downloadImage(data.getData().toString());
                            }
                        } else {
                            //网络失败
                            if (data.getData() != null) {
                                //toast.setIcon(R.drawable.ic_toast_error);
                                //toast.show(backData.getObject().toString());
                            }
                        }
                        //}
                    } else {
                        //网络失败

                    }
                    break;
                case DOWNLOAD_SUCCESS:
                    String filePath = CacheManager.getInstance().getCachePath(CommonUtils.md5(url), CacheManagerConst.CacheType.CACHE_NETWORK);
                    File downloadFile = new File(filePath + ".temp");
                    File file = new File(filePath + "." + formatType);
                    if (downloadFile.exists()) {
                        downloadFile.renameTo(file);
                    }
                    break;
                case LOCAL_GIF:
                    //展示本地图片
                    ivLoading.setVisibility(View.GONE);
                    showGif();
                    break;
                case NET_GIF:
                    ivLoading.setVisibility(View.GONE);
                    String filePathGif = CacheManager.getInstance().getCachePath(CommonUtils.md5(url), CacheManagerConst.CacheType.CACHE_NETWORK);
                    // 设置背景gif图片资源
                    try {
                        gbDrawable = new GifDrawable(filePathGif + ".gif");
                        //gbDrawable.setLoopCount(4);//设置循环次数
                        gifView.setImageDrawable(gbDrawable);
                        jumpActivity(0);
                    } catch (Resources.NotFoundException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                        bit = BitmapFactory.decodeFile(filePathGif + ".gif");
                        if (bit != null) {
                            gifView.setImageBitmap(bit);
                            jumpActivity(2000);
                        } else {
                            try {
                                gbDrawable = new GifDrawable(getResources(), R.drawable.loading);
                                //gbDrawable.setLoopCount(4);//设置循环次数
                                gifView.setImageDrawable(gbDrawable);
                            } catch (Resources.NotFoundException e11) {
                                // TODO Auto-generated catch block
                                e11.printStackTrace();
                            } catch (IOException e11) {
                                // TODO Auto-generated catch block
                                e11.printStackTrace();
                            }
                            jumpActivity(0);
                        }
                    }
                    break;
                case NET_JPG:
                    ivLoading.setVisibility(View.GONE);
                    String filePathPng = CacheManager.getInstance().getCachePath(CommonUtils.md5(url), CacheManagerConst.CacheType.CACHE_NETWORK);
                    gifView.setImageBitmap(android.graphics.BitmapFactory.decodeFile(filePathPng + ".png"));
                    jumpActivity(3000);
                    break;
                default:
                    break;
            }
        }

    };
    private boolean ispush;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏
        super.onCreate(savedInstanceState);
    }

     public void initData() {
//        CheckRootUtils utils=new CheckRootUtils();
//        boolean isRoot=utils.isDeviceRooted();
        //isRoot=false;
        if(false){
//            ivLoading.setVisibility(View.VISIBLE);
//            gifView.setVisibility(View.GONE);
//            remindUi=new DialogRemindUi(
//                    new android.view.View.OnClickListener() {
//
//                        @Override
//                        public void onClick(View v) {
//                            remindUi.dismiss();
//                            finish();
//                        }
//                    });
//            remindUi.setTitleTxt(getString(R.string.remind));
//            remindUi.setShowTxt("您的手机不是预装系统,请更换手机使用!");
//            remindUi.setConfirmTxt(getString(R.string.confirm));
//            remindUi.show();
        }else{
            isGuide="true";
            if(isGuide==null||isGuide.equals("")){
//                Intent intent=new Intent(LoadingActivity.this, GuideViewPagerActivity.class);
//                startActivity(intent);
//                finish();
            }else{
                String filePath=CacheManager.getInstance().getCachePath(CommonUtils.md5(url), CacheManagerConst.CacheType.CACHE_NETWORK);
                File file=new File(filePath+".gif");
                if(file.exists()){
                    Timer timer=new Timer();
                    TimerTask task=new TimerTask() {
                        @Override
                        public void run() {
                            mHandler.sendEmptyMessage(NET_GIF);
                        }
                    };
                    timer.schedule(task, 300);
                }else if(new File(filePath+".png").exists()){
                    Timer  timer=new Timer();
                    TimerTask task=new TimerTask() {

                        @Override
                        public void run() {
                            mHandler.sendEmptyMessage(NET_JPG);
                        }
                    };
                    timer.schedule(task, 300);
                }else {
                    //ivLoading.setVisibility(View.GONE);
                    Timer  timer=new Timer();
                    TimerTask task=new TimerTask() {

                        @Override
                        public void run() {
                            mHandler.sendEmptyMessage(LOCAL_GIF);
                        }
                    };
                    timer.schedule(task, 300);
                }
            }
        }
    }

    @Override
    public void initListener() {

    }

    public void initView() {
        gifView = (GifImageView)findViewById(R.id.gif_loading);
        ivLoading = (ImageView)findViewById(R.id.iv_loading);
    }

    public void initBaseData() {
        ispush = getIntent().getBooleanExtra("isPush", false);

        setContentView(R.layout.activity_loading);
        SPUtils.put(SPConst.IS_LOGIN,"");
        CommonUtils.addTimeOne();
//        CommonParameters commonP=CommonParameters.getInstance();
//        commonP.setToken("");
//        MyMainActivity.PAGE_TYPE=MyMainActivity.LOGIN;
        isGuide=(String)SPUtils.getOject(SPConst.IS_GUIDE, "");
//        toast=ToastView.getInstance();
        SPUtils.put(SPConst.IS_APP_ON_FOREGROUND,false);

        netService= NetService.getInstance();
        netService.clearParams();
        netService.setHttpMethod(Code.HttpSetting.GET_MODE);
        netService.setUrl(url);
        netService.setParams("type", "0");
        netService.loader(new NetLoadListener() {
            @Override
            public void onloaderListener(BackData result) {
                netService.setRunning(false);
                Message msg=new Message();
                msg.what=VERSION;
                msg.obj=result;
                mHandler.sendMessage(msg);
            }
        });
    }
    private  void downloadImage(String imageUrl){
        String filePath= CacheManager.getInstance().getCachePath(CommonUtils.md5(url), CacheManagerConst.CacheType.CACHE_NETWORK)+".temp";
        if(imageUrl!=null&!imageUrl.equals("")){
            formatType=imageUrl.substring(imageUrl.lastIndexOf(".")+1,imageUrl.length());
            if(formatType.toLowerCase().equals("gif".toLowerCase())){
                formatType="gif";
            }else if(formatType.toLowerCase().equals("jpg".toLowerCase())||formatType.toLowerCase().equals("png".toLowerCase())){
                formatType="png";
            }else{
                formatType="gif";
            }
        }
        HttpUtils http = new HttpUtils();
        HttpHandler handler = http.download(imageUrl,filePath,
                false, // 如果目标文件存在，接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
                false, // 如果从请求返回信息中获取到文件名，下载完成后自动重命名。
                new RequestCallBack<File>() {

                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<File> responseInfo) {
                        Message msg=new Message();
                        msg.what=DOWNLOAD_SUCCESS;
                        msg.obj=responseInfo.result.getPath();
                        mHandler.handleMessage(msg);
                    }

                    @Override
                    public void onFailure(com.lidroid.xutils.exception.HttpException e, String s) {

                    }
                });
    }
    /**
     * 展示gif
     */
    private void showGif(){

        // 设置背景gif图片资源
        try {
            gbDrawable=new GifDrawable(getResources(), R.drawable.loading);
            //gbDrawable.setLoopCount(4);//设置循环次数
            gifView.setImageDrawable(gbDrawable);
        } catch (Resources.NotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        jumpActivity(0);
    }
    /**
     * 跳转
     */
    private void jumpActivity(int time){
        if(time==0){
            time= gbDrawable.getDuration();
        }

        if(time==0){
            time=3000;
        }

        Timer  timer=new Timer();
        TimerTask task=new TimerTask() {

            @Override
            public void run() {
                Intent intent=new Intent(LoadingActivity.this, MainActivity.class);
                intent.putExtra("isJump", true);
                if(ispush){
                    intent.putExtra("isPush", ispush);
                    Bundle bundle=getIntent().getExtras();
                    intent.putExtras(bundle);
                }
                Intent i =getIntent();
                String action =i.getAction();
                if(Intent.ACTION_VIEW.equals(action)){
                    Uri uri =i.getData();
                    if(uri!=null){
                        intent.putExtra("isWeb",true);
                        intent.putExtra("uri", uri);
                    }
                }
                startActivity(intent);
                finish();
            }
        };
        timer.schedule(task, time-200);
    }
}
